package io;

import  java.util.Scanner;

//主程序入口
public class Main {
    private  static ImageManager imageManager;
    private static Scanner scanner;

    public static void main(String[] args){
        initialize();
        showWelcome();
        runMainLoop();
        cleabup();
    }

    //初始化资源
    private static void initialize(){
        imageManager = new ImageManager();
        scanner = new Scanner(System.in);
        System.out.println("系统初始换完成...");
    }

    //显示欢迎信息
    private static void showWelcome(){
        System.out.println("==========================================");
        System.out.println("        网络图片下载与管理系统");
        System.out.println("==========================================");
        System.out.println("当前已管理图片: " + imageManager.getImageCount() + " 张");
    }

    //主循环
    private static void runMainLoop(){
        boolean running = true;
        while (running){
            showMenu();
            String choice = scanner.nextLine().trim();

            switch (choice){
                case "1":
                    downloadImage();
                    break;
                case "2":
                    listImages();
                    break;
                case "3":
                    searchImages();
                    break;
                case "4":
                    running = false;
                    break;
                default:
                    System.out.println("无效选择，请重新输入！");
            }

            if (running){
                System.out.println("\n按回车键继续...");
                scanner.nextLine();
            }
        }
    }

    //显示主菜单
    private static void showMenu(){
        System.out.println("\n=== 图片下载系统 ===");
        System.out.println("1. 下载图片");
        System.out.println("2. 查看所有图片");
        System.out.println("3. 搜索图片");
        System.out.println("4. 退出");
        System.out.print("请选择操作 (1-4): ");
    }

    //下载图片功能
    private static void downloadImage(){
        System.out.println("\n=== 下载图片 ===");
        System.out.println("请输入图片URL：");
        String url = scanner.nextLine().trim();

        if (url.isEmpty()){
            System.out.println("URL不能为空！");
            return;
        }

        System.out.println("开始下载...");
        imageManager.downloadImage(url);
    }

    //列出所有图片
    private static void listImages(){
        System.out.println("\n=== 图片列表 ===");
        imageManager.listImages();
    }

    //搜索图片
    private static void searchImages(){
        System.out.println("\n===搜索图片===");
        System.out.print("请输入关键词：");
        String keyword = scanner.nextLine().trim();

        if (keyword.isEmpty()){
            System.out.println("搜索关键词不能为空！");
            return;
        }

        imageManager.searchImage(keyword);
    }

    //清理资源
    private static void cleabup(){
        if (scanner != null){
            scanner.close();
        }
        System.out.println("\n感谢使用网络图片下载与管理系统");
        System.out.println("程序已退出。");
    }
}
